/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MyOwnChat;

/**
 *
 * @author lubinchen
 */



import java.net.*;
import java.io.*;
import java.lang.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;


public class LubinServerThread extends Thread {

      public Lubinchat chat=null;
      public Socket socket=null;
      public String clientname="noName";
      public String clientIP=null;

     private DataInputStream  streamIn  =  null;
     private DataOutputStream streamOut = null;

 

    public LubinServerThread(String name, Socket connected_one, Lubinchat Bigchat, int clientCount){
        //clientname= "User";
        //String tempt=null;
       // tempt= Integer.toString(clientCount);
       // clientname= clientname.concat(tempt);
        clientname=name;
        socket=connected_one;
        chat=Bigchat;
        clientIP= connected_one.getInetAddress().toString().substring(1);
    }



   public void open() throws IOException
   {  streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
      streamOut = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
   }


   public void close() throws IOException
   {  if (socket != null)    socket.close();
      if (streamIn != null)  streamIn.close();
      if (streamOut != null) streamOut.close();
   }



    public void run()
   {
      System.out.println("Thread " + clientname + " is running.");

      while (true)
      {  try
         {  chat.handle(clientname, streamIn.readUTF());
         }
         catch(IOException ioe)
         {  System.out.println(clientname + "caused ERROR reading: " + ioe.getMessage());
            chat.remove(clientname);
            stop();
         }
      }
   }



     public void send(String msg)
   {   try
       {  streamOut.writeUTF(msg);
          streamOut.flush();
       }
       catch(IOException ioe)
       {  //System.out.println(clientname + " ERROR sending: " + ioe.getMessage());
          System.out.println(clientname + " has left. Bye bye~ ");
          chat.remove(clientname);
          stop();
       }
   }

}
